<?php

namespace App\Http\Lib;
use App\Http\Lib\ResBase;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use http\Env;
use function PHPUnit\Framework\isEmpty;

class TokenServise
{
    protected static $key;

    //生成token
    public static function createToken($user_id){
        $key = env('APP_KEY');
        //生成token
        $payload = array(
            "iss" => "",
            "aud" => "",
            "iat" => time(),
            "nbf" => time(),
            "exp" => time()+604800,
            "uid" => $user_id
        );

        $jwt = JWT::encode($payload,$key,'HS256');
        return $jwt;
    }


    //解密token
    public static function decodeToken($jwt){
        $key = env('APP_KEY');
        if(isEmpty($jwt)){
            return ResBase::ApiRes(400,'未登录','failed');
        }
        try {
            $decode = JWT::decode($jwt,new Key($key,'HS256'));
        } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            return ResBase::ApiRes(501,'身份已过期','failed');
        }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            return ResBase::ApiRes(501,'身份已过期','failed');
        }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
            echo $e->getMessage();
        } catch (\Exception $e){
            return ResBase::ApiRes(501,'身份已过期','failed');
        }
    }
}
